import sys
import os
import traceback

from util import LogUtil, MessageUtil, ThemeUtil
from view.MainWindow import MainWindow
from PySide6.QtWidgets import QApplication, QMessageBox
from PySide6.QtGui import QFont, QIcon


def createDir():
    """建立文件夹"""
    paths = [
        "log",
    ]
    for path in paths:
        if not os.path.exists(path):
            os.makedirs(path)


def handleException(ty, value, tb):
    """
    处理异常
    :param ty: 异常的类型
    :param value: 异常的对象
    :param tb: 异常的tb
    """
    # 调用默认异常处理
    sys.__excepthook__(ty, value, tb)
    # 自己处理异常
    traceback_string = ''.join(
        traceback.format_exception(ty, value, tb))
    LogUtil.logger.critical(traceback_string)
    button = MessageUtil.confirm(QMessageBox.Icon.Critical, "错误",
                                 "{}".format(traceback_string), yesText="退出程序", noText="继续运行")
    if button == QMessageBox.StandardButton.Yes:
        sys.exit(1)


if __name__ == "__main__":

    # 建立文件夹
    createDir()

    # 设置日志
    LogUtil.initLogger()

    # 定向异常
    sys.excepthook = handleException

    # 创建应用实例
    app = QApplication(sys.argv)
    app.setStyle("Fusion")
    font = app.font()
    font.setHintingPreference(QFont.HintingPreference.PreferNoHinting)
    app.setFont(font)
    app.setWindowIcon(QIcon('logo.png'))

    # 设定主题
    ThemeUtil.init_theme("dark_teal.qss", app)

    # 创建主窗口
    window = MainWindow()

    # 显示窗口
    window.show()

    # 进入应用主循环
    sys.exit(app.exec())
